﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

namespace Jerkymon.Data
{
    public class DataSetUtils
    {
		#region Static Methods (6)
		// 
        /// <summary>
        /// Howto: Export a dataset to Excel (c# / asp.net)
        /// Reference URL : http://tim.mackey.ie/HowtoExportADatasetToExcelCAspnet.aspx
        /// </summary>
        /// <param name="ds"></param>
        /// <param name="filename"></param>
        public static void ExportDataSetToExcel(DataSet ds, string filename)
        {
            HttpResponse response = HttpContext.Current.Response;

            // first let's clean up the response.object
            response.Clear();
            response.Charset = "";

            // set the response mime type for excel
            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");

            // create a string writer
            using (StringWriter sw = new StringWriter())
            {
                using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                {
                    // instantiate a datagrid
                    DataGrid dg = new DataGrid();
                    dg.DataSource = ds.Tables[0];
                    dg.DataBind();
                    dg.RenderControl(htw);
                    response.Write(sw.ToString());
                    response.End();
                }
            }
        }

		public static void ExportToExcel(DataSet source, string fileName)
        {

            HttpResponse response = HttpContext.Current.Response;

            // first let's clean up the response.object
            response.Clear();
            response.Charset = "";

            // set the response mime type for excel
            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");

            //System.IO.StreamWriter excelDoc;

            using (StringWriter excelDoc = new StringWriter())
            {
                using (HtmlTextWriter htw = new HtmlTextWriter(excelDoc))
                {

                    //excelDoc = new System.IO.StreamWriter(fileName);
                    const string startExcelXML = "<xml version>\r\n<Workbook " +
                              "xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n" +
                              " xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n " +
                              "xmlns:x=\"urn:schemas-    microsoft-com:office:" +
                              "excel\"\r\n xmlns:ss=\"urn:schemas-microsoft-com:" +
                              "office:spreadsheet\">\r\n <Styles>\r\n " +
                              "<Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n " +
                              "<Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>" +
                              "\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>" +
                              "\r\n <Protection/>\r\n </Style>\r\n " +
                              "<Style ss:ID=\"BoldColumn\">\r\n <Font " +
                              "x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n " +
                              "<Style     ss:ID=\"StringLiteral\">\r\n <NumberFormat" +
                              " ss:Format=\"@\"/>\r\n </Style>\r\n <Style " +
                              "ss:ID=\"Decimal\">\r\n <NumberFormat " +
                              "ss:Format=\"0.0000\"/>\r\n </Style>\r\n " +
                              "<Style ss:ID=\"Integer\">\r\n <NumberFormat " +
                              "ss:Format=\"0\"/>\r\n </Style>\r\n <Style " +
                              "ss:ID=\"DateLiteral\">\r\n <NumberFormat " +
                              "ss:Format=\"mm/dd/yyyy;@\"/>\r\n </Style>\r\n " +
                              "</Styles>\r\n ";
                    const string endExcelXML = "</Workbook>";

                    int rowCount = 0;
                    int sheetCount = 1;
                    /*
                   <xml version>
                   <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
                   xmlns:o="urn:schemas-microsoft-com:office:office"
                   xmlns:x="urn:schemas-microsoft-com:office:excel"
                   xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
                   <Styles>
                   <Style ss:ID="Default" ss:Name="Normal">
                     <Alignment ss:Vertical="Bottom"/>
                     <Borders/>
                     <Font/>
                     <Interior/>
                     <NumberFormat/>
                     <Protection/>
                   </Style>
                   <Style ss:ID="BoldColumn">
                     <Font x:Family="Swiss" ss:Bold="1"/>
                   </Style>
                   <Style ss:ID="StringLiteral">
                     <NumberFormat ss:Format="@"/>
                   </Style>
                   <Style ss:ID="Decimal">
                     <NumberFormat ss:Format="0.0000"/>
                   </Style>
                   <Style ss:ID="Integer">
                     <NumberFormat ss:Format="0"/>
                   </Style>
                   <Style ss:ID="DateLiteral">
                     <NumberFormat ss:Format="mm/dd/yyyy;@"/>
                   </Style>
                   </Styles>
                   <Worksheet ss:Name="Sheet1">
                   </Worksheet>
                   </Workbook>
                   */
                    excelDoc.Write(startExcelXML);
                    excelDoc.Write("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
                    excelDoc.Write("<Table>");
                    excelDoc.Write("<Row>");
                    for (int x = 0; x < source.Tables[0].Columns.Count; x++)
                    {
                        excelDoc.Write("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");
                        excelDoc.Write(source.Tables[0].Columns[x].ColumnName);
                        excelDoc.Write("</Data></Cell>");
                    }
                    excelDoc.Write("</Row>");
                    foreach (DataRow x in source.Tables[0].Rows)
                    {
                        rowCount++;
                        //if the number of rows is > 64000 create a new page to continue output
                        if (rowCount == 64000)
                        {
                            rowCount = 0;
                            sheetCount++;
                            excelDoc.Write("</Table>");
                            excelDoc.Write(" </Worksheet>");
                            excelDoc.Write("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
                            excelDoc.Write("<Table>");
                        }
                        excelDoc.Write("<Row>"); //ID=" + rowCount + "
                        for (int y = 0; y < source.Tables[0].Columns.Count; y++)
                        {
                            System.Type rowType;
                            rowType = x[y].GetType();
                            switch (rowType.ToString())
                            {
                                case "System.String":
                                    string XMLstring = x[y].ToString();
                                    XMLstring = XMLstring.Trim();
                                    XMLstring = XMLstring.Replace("&", "&");
                                    XMLstring = XMLstring.Replace(">", ">");
                                    XMLstring = XMLstring.Replace("<", "<");
                                    excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                        "<Data ss:Type=\"String\">");
                                    excelDoc.Write(XMLstring);
                                    excelDoc.Write("</Data></Cell>");

                                    break;
                                case "System.DateTime":
                                    //Excel has a specific Date Format of YYYY-MM-DD followed by  
                                    //the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000
                                    //The Following Code puts the date stored in XMLDate 
                                    //to the format above
                                    DateTime XMLDate = (DateTime)x[y];
                                    string XMLDatetoString = ""; //Excel Converted Date
                                    XMLDatetoString = XMLDate.Year.ToString() +
                                        "-" +
                                        (XMLDate.Month < 10 ? "0" +
                                        XMLDate.Month.ToString() : XMLDate.Month.ToString()) +
                                        "-" +
                                        (XMLDate.Day < 10 ? "0" +
                                        XMLDate.Day.ToString() : XMLDate.Day.ToString()) +
                                        "T" +
                                        (XMLDate.Hour < 10 ? "0" +
                                        XMLDate.Hour.ToString() : XMLDate.Hour.ToString()) +
                                        ":" +
                                        (XMLDate.Minute < 10 ? "0" +
                                        XMLDate.Minute.ToString() : XMLDate.Minute.ToString()) +
                                        ":" +
                                        (XMLDate.Second < 10 ? "0" +
                                        XMLDate.Second.ToString() : XMLDate.Second.ToString()) +
                                        ".000";
                                    excelDoc.Write("<Cell ss:StyleID=\"DateLiteral\">" +
                                        "<Data ss:Type=\"DateTime\">");
                                    excelDoc.Write(XMLDatetoString);
                                    excelDoc.Write("</Data></Cell>");

                                    break;
                                case "System.Boolean":
                                    excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                        "<Data ss:Type=\"String\">");
                                    excelDoc.Write(x[y].ToString());
                                    excelDoc.Write("</Data></Cell>");
                                    break;
                                case "System.Int16":
                                case "System.Int32":
                                case "System.Int64":
                                case "System.Byte":
                                    excelDoc.Write("<Cell ss:StyleID=\"Integer\">" +
                                        "<Data ss:Type=\"Number\">");
                                    excelDoc.Write(x[y].ToString());
                                    excelDoc.Write("</Data></Cell>");

                                    break;
                                case "System.Decimal":
                                case "System.Double":
                                    excelDoc.Write("<Cell ss:StyleID=\"Decimal\">" +
                                        "<Data ss:Type=\"Number\">");
                                    excelDoc.Write(x[y].ToString());
                                    excelDoc.Write("</Data></Cell>");

                                    break;
                                case "System.DBNull":
                                    excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                        "<Data ss:Type=\"String\">");
                                    excelDoc.Write("");
                                    excelDoc.Write("</Data></Cell>");

                                    break;
                                default:
                                    throw (new Exception(rowType.ToString() + " not handled."));
                            }
                        }
                        excelDoc.Write("</Row>");
                    }
                    excelDoc.Write("</Table>");
                    excelDoc.Write(" </Worksheet>");
                    excelDoc.Write(endExcelXML);
                    //excelDoc.Close();
                    response.Write(excelDoc.ToString());
                    response.Flush();
                    response.End();
                    response.Close();

                }
            }

            //response.Write(excelDoc.ToString());
            //response.End();

        }

		public static DataSet GetDataSet(string uri)
        {
            // Create the web request  
            HttpWebRequest request
                = WebRequest.Create(uri) as HttpWebRequest;

            // Load data into a dataset  
            DataSet ds = new DataSet();

            // Get response  
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {

                try
                {
                    ds.ReadXml(response.GetResponseStream());
                    return ds;
                }
                //catch (Exception ex)
                catch
                {
                    return null;
                }
            }

            //return ds;
        }

		public static string GetFromFile(string path)
        {
            string text2;
            try
            {
                StreamReader reader1 = new StreamReader(File.OpenRead(HttpContext.Current.Server.MapPath(path)));
                reader1.BaseStream.Seek((long)0, SeekOrigin.Begin);
                string text1 = reader1.ReadToEnd();
                reader1.Close();
                text2 = text1;
            }
            catch
            {
                try
                {
                    StreamReader reader1 = new StreamReader(File.OpenRead(path));
                    reader1.BaseStream.Seek((long)0, SeekOrigin.Begin);
                    string text1 = reader1.ReadToEnd();
                    reader1.Close();
                    text2 = text1;
                }
                catch
                {
                    text2 = "";
                }
            }
            return text2;
        }

		public static DataSet GetXMLData(string xmlfile)
        {
            DataSet set2;

            XmlTextReader reader1 = new XmlTextReader(xmlfile);
            DataSet set1 = new DataSet();
            set1.ReadXml(reader1);
            try
            {
                set2 = set1;
            }
            catch (Exception)
            {
                set2 = set1;
            }
            finally
            {
                reader1.Close();
            }
            return set2;
        }

		public static DataSet GetXMLFile(string xmlfile)
        {
            DataSet set2;
            string text1 = xmlfile;
            FileStream stream1 = new FileStream(text1, FileMode.Open);
            XmlTextReader reader1 = new XmlTextReader(stream1);
            DataSet set1 = new DataSet();
            set1.ReadXml(reader1);
            try
            {
                set2 = set1;
            }
            catch (Exception)
            {
                set2 = set1;
            }
            finally
            {
                reader1.Close();
            }
            return set2;
        }
		#endregion
    }


    /// <summary>
    /// DataSet Extensions.
    /// URL : http://www.eggheadcafe.com/tutorials/aspnet/d841d7b9-d3d2-4947-8e79-a5c03cbf88fb/extension-methods-for-dat.aspx
    /// </summary>
    public static class DataSetExtensions
    {
		#region Static Methods (9)
		/// <summary>
        /// Gets the data set sizein bytes.
        /// </summary>
        /// <param name="dataSet">The data set.</param>
        /// <returns></returns>
        public static int GetDataSetSizeinBytes(this DataSet dataSet)
        {
            if (dataSet != null)
            {

                MemoryStream stream = new MemoryStream();
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                binaryFormatter.Serialize(stream, dataSet);

                stream.Seek(0, 0);
                byte[] result = stream.ToArray();

                stream.Close();

                return result.Length;
            }
            else
                return 0;
        }

		/// <summary>
        /// Gets the table errors.
        /// </summary>
        /// <param name="dataset">The dataset.</param>
        /// <param name="tableName">Name of the table.</param>
        /// <returns></returns>
        public static string GetTableErrors(this DataSet dataset, string tableName)
        {
            string error = string.Empty;

            if (dataset.HasTableErrors(tableName))
            {
                foreach (DataRow row in dataset.Tables[tableName].GetErrors())
                {
                    foreach (DataColumn column in row.GetColumnsInError())
                    {
                        error += string.Format("Error : {0}"
                                                        , row.GetColumnError(column));
                    }
                }
            }
            return error;
        }

		/// <summary>
        /// Gets the tables count.
        /// </summary>
        /// <param name="dataSet">The data set.</param>
        /// <returns></returns>
        public static int GetTablesCount(this DataSet dataSet)
        {
            if (!dataSet.IsEmpty())
                return dataSet.Tables.Count;
            else
                return 0;
        }

		/// <summary>
        /// Determines whether the specified data set has constraints.
        /// </summary>
        /// <param name="dataSet">The data set.</param>
        /// <param name="tableName">Name of the table.</param>
        /// <returns>
        ///     <c>true</c> if the specified data set has constraints; otherwise, <c>false</c>.
        /// </returns>
        public static bool HasConstraints(this DataSet dataSet, string tableName)
        {
            return (dataSet.Tables[tableName].Constraints.Count > 0 ? true : false);
        }

		/// <summary>
        /// Determines whether the specified data set has errors.
        /// </summary>
        /// <param name="dataSet">The data set.</param>
        /// <param name="tableName">Name of the table.</param>
        /// <returns>
        ///     <c>true</c> if the specified data set has errors; otherwise, <c>false</c>.
        /// </returns>
        public static bool HasTableErrors(this DataSet dataSet, string tableName)
        {
            return (dataSet.Tables[tableName].HasErrors);
        }

		/// <summary>
        /// Determines whether the specified data set is empty.
        /// </summary>
        /// <param name="dataSet">The data set.</param>
        /// <returns>
        ///     <c>true</c> if the specified data set is empty; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsEmpty(this DataSet dataSet)
        {
            bool isEmpty = false;

            if (dataSet == null)
            {
                isEmpty = true;
            }
            else
            {
                if (dataSet.Tables.Count == 0)
                {
                    isEmpty = true;
                }
                else
                {
                    isEmpty = dataSet.Tables[0].Rows.Count == 0 ? true : false;
                }

            }
            return isEmpty;
        }

		public static DataTable ListToDataTable<T>(List<T> list)
        {
            DataTable dt;

            string[] className = typeof(T).FullName.Split('+');
            string tableName;

            tableName = className[className.Length - 1];

            //dt = new DataTable(typeof(T).FullName);

            dt = new DataTable(tableName);

            foreach (PropertyInfo info in typeof(T).GetProperties())
            {
                dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));
            }

            foreach (T t in list)
            {
                DataRow dr = dt.NewRow();

                foreach (PropertyInfo info in typeof(T).GetProperties())
                {
                    dr[info.Name] = info.GetValue(t, null);
                }
                dt.Rows.Add(dr);
            }

            return dt;
        }

		/// <summary>
        /// Selects the duplicates.
        /// </summary>
        /// <param name="dataTable">The data table.</param>
        /// <param name="columnName">Name of the column.</param>
        /// <returns></returns>
        public static List<object> SelectDuplicates(this DataTable dataTable, string columnName)
        {
            List<object> duplicates = new List<object>();

            for (int iValue = 0; iValue < dataTable.Rows.Count; iValue++)
            {
                object lastValue = dataTable.Rows[iValue][columnName];
                if (duplicates.Contains(lastValue))
                    duplicates.Add(lastValue);
            }
            return duplicates;
        }

		/// <summary>
        /// Selects the uniques.
        /// </summary>
        /// <param name="dataTable">The data table.</param>
        /// <param name="columnName">Name of the column.</param>
        /// <returns></returns>
        public static List<object> SelectUniques(this DataTable dataTable, string columnName)
        {
            List<object> uniques = new List<object>();

            for (int iValue = 0; iValue < dataTable.Rows.Count; iValue++)
            {
                object lastValue = dataTable.Rows[iValue][columnName];
                if (!uniques.Contains(lastValue))
                    uniques.Add(lastValue);
            }
            return uniques;
        }
		#endregion
    }

    static public class PublicationFactory
    {
		#region Static Methods (1)
		/// <summary>
        /// Create a diffgram from two datasets
        /// diffgram contains the list of row to create, update and delete to pass from old to new step
        /// old and new datasets must have the same schema
        /// the old dataset give the list of table to compute
        /// Is supposed that all data have a ToString() method wich render a representative value of the data
        /// Is supposed that a column named "PK" got a unique string identifier
        /// URL : http://www.eggheadcafe.com/tutorials/aspnet/2eb80099-3611-43e0-82da-1d5889195d55/comparing-datasets-using.aspx
        /// </summary>
        /// <param name="oldDataSet">Old step</param>
        /// <param name="newDataSet">Current step</param>
        /// <returns>diffgram as dataset</returns>
        static public DataSet DeltaMaker(DataSet oldDataSet, DataSet newDataSet)
        {
            DataSet datasetdiff;
            DataRow tempRow;
            DataTable tempTable;
            string tempTableName;
            datasetdiff = new DataSet();

            // concat all data of each field, in order to compare content
            TTSDataHelper.BeginSerializeHelper(oldDataSet);
            TTSDataHelper.BeginSerializeHelper(newDataSet);

            for (int i = 0; i < oldDataSet.Tables.Count; i++)
            {
                tempTableName = oldDataSet.Tables[i].TableName;
                IEnumerable<DataRow> orig = oldDataSet.Tables[tempTableName].AsEnumerable();
                IEnumerable<DataRow> updated = newDataSet.Tables[tempTableName].AsEnumerable();

                IEnumerable<DataRow> Added = // in updated, wich don't exist in origin
                    from u in updated
                    where !(from o in orig
                            select o.Field<string>("PK"))
                        .Contains(u.Field<string>("PK"))
                    select u;
                IEnumerable<DataRow> Modif = //  in updated, data different from origin
                    from u in updated
                    where !(from o in orig
                            select o.Field<string>("SERIALIZED"))
                        .Contains(u.Field<string>("SERIALIZED"))
                        && !(from a in Added select a.Field<string>("PK")) // ignore just added
                             .Contains(u.Field<string>("PK"))
                    select u;
                IEnumerable<DataRow> Deleted = // in origin, non existing in updated
                    from o in orig
                    where !(from u in updated
                            select u.Field<string>("PK"))
                        .Contains(o.Field<string>("PK"))
                    select o;

                datasetdiff.Tables.Add(oldDataSet.Tables[tempTableName].Clone());
                tempTable = datasetdiff.Tables[tempTableName];
                tempTable.BeginLoadData();

                // Create, accept then delete
                foreach (DataRow row in Deleted)
                {
                    tempRow = tempTable.Rows.Add(row.ItemArray);
                    tempRow.AcceptChanges();
                    tempRow.Delete();
                }

                // Create added
                foreach (DataRow row in Added)
                {
                    tempRow = tempTable.Rows.Add(row.ItemArray);
                    tempRow.AcceptChanges();
                    tempRow.SetAdded();
                }
                // Create modified
                foreach (DataRow row in Modif)
                {
                    tempRow = tempTable.Rows.Add(row.ItemArray);
                    tempRow.AcceptChanges();
                    tempRow.SetModified();
                }
                tempTable.EndLoadData();

                tempTable.Columns.Remove("SERIALIZED");
            }

            //remove data comparison helper
            TTSDataHelper.EndSerializeHelper(oldDataSet);
            TTSDataHelper.EndSerializeHelper(newDataSet);

            return datasetdiff;
        }
		#endregion
    }

    internal static class TTSDataHelper
    {
		#region Static Fields (1)
		public static char separator = '§';
		#endregion

		#region Static Methods (2)
		public static void BeginSerializeHelper(DataSet dataset)
        {
            string serialized;
            foreach (DataTable table in dataset.Tables)
            {
                table.Columns.Add("SERIALIZED", typeof(string));
                foreach (DataRow row in table.Rows)
                {
                    serialized = string.Empty;
                    for (int i = 0; i < table.Columns.Count - 2; i++)
                    {
                        serialized += row[i].ToString() + separator;
                    }
                    row["SERIALIZED"] = serialized;
                }
            }
        }

		public static void EndSerializeHelper(DataSet dataSet)
        {
            foreach (DataTable table in dataSet.Tables)
            {
                table.Columns.Remove("SERIALIZED");
            }
        }
		#endregion
    }

    /// <summary>
    /// http://unboxedsolutions.com/sean/archive/2009/06/06/15961.aspx
    /// </summary>
    public static class Extensions
    {
		#region Static Methods (1)
		public static DataTable AsDataTable<T>(this IEnumerable<T> enumberable)
        {
            //DataTable table = new DataTable("Generated");
            DataTable table = new DataTable();

            T first = enumberable.FirstOrDefault();
            if (first == null)
                return table;

            PropertyInfo[] properties = first.GetType().GetProperties();
            //foreach (PropertyInfo pi in properties)
            //    table.Columns.Add(pi.Name, pi.PropertyType);

            foreach (PropertyInfo pi in properties)
            {
                Type colType = pi.PropertyType; if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                {
                    colType = colType.GetGenericArguments()[0];
                }

                //dtReturn.Columns.Add(new DataColumn(pi.Name, colType));

                //table.Columns.Add(pi.Name, pi.PropertyType);
                table.Columns.Add(new DataColumn(pi.Name, colType));

            }

            foreach (T t in enumberable)
            {
                DataRow row = table.NewRow();
                foreach (PropertyInfo pi in properties)
                    row[pi.Name] = t.GetType().InvokeMember(pi.Name, BindingFlags.GetProperty, null, t, null);
                table.Rows.Add(row);
            }

            return table;
        }
		#endregion
    }
}
